package cn.ichiva.dl.tushare.analy.ws;

import cn.ichiva.common.DataHelper;
import cn.ichiva.dl.tushare.analy.impl.Statistical;
import cn.ichiva.dl.tushare.analy.impl.TradeAgent;
import cn.ichiva.dl.tushare.analy.impl.TradeAgentList;
import cn.ichiva.dl.tushare.analy.AgentConfig2442;
import cn.ichiva.dl.tushare.common.ScoreAgent;
import lombok.extern.slf4j.Slf4j;

import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.concurrent.atomic.AtomicInteger;

/**
 *
 *
 * Created by game group on 2020/12/8.
 */
@Slf4j
public class AgentListServer extends SessionWebSocketServer {

    private final TradeAgentList tradeAgentList;

    public static void main(String[] args) {
        ArrayList<TradeAgent> initAgent = new ArrayList<>();
        for (int i = 0; i < 8; i++) {
            initAgent.add(new TradeAgent(AgentConfig2442.getInstance()));
        }
        new AgentListServer(10948, initAgent).start();
    }

    public AgentListServer(int port, Collection<TradeAgent> initAgent){
        super(new InetSocketAddress(port));
        this.tradeAgentList = new TradeAgentList(initAgent);
    }

    AtomicInteger index = new AtomicInteger();
    long time = System.currentTimeMillis();
    /**
     * 1.取ai的消息
     * 2.处理结果
     * @param session
     * @param message
     */
    @Override
    protected void onMessage(WebsocketSession session, ByteBuffer message) {
        byte[] array = message.array();
        WSRequest req = (WSRequest) DataHelper.toObject(array);

        if (log.isDebugEnabled()) {
            log.debug("byte buffer = {}",req);
        }

        WSResponse res = null;
        if (ApiEnum.AGENT_LIST.getAction().equals(req.getAction())) {  //获取排行榜
            res = new WSResponse();
            res.setAction(ApiEnum.AGENT_LIST.getAction());
            res.setData(new ArrayList<>(tradeAgentList.getList()));
        }else if(ApiEnum.TRAIN_RES.getAction().equals(req.getAction())){ //训练结果
            TradeAgent agent = (TradeAgent) req.getData();
            log.info("训练结果 agent = {}",agent);
            ScoreAgent scoreAgent = tradeAgentList.put(agent);
            if(null != scoreAgent){
                Statistical.writeAgent(agent);
            }

            WSResponse wsResponse = new WSResponse();
            wsResponse.setAction(ApiEnum.PUT_LIST.getAction());
            wsResponse.setData(Arrays.asList(agent));
            broadcastObject(wsResponse);
        }

        Integer id = req.getId();
        if(null != id) {
            if(null == res) res = new WSResponse();
            res.setId(id);
        }

        if(null != res) {
            sendObject(session,res);
        }
    }

    private void broadcastObject(WSResponse wsResponse) {
        byte[] bytes = DataHelper.toByte(wsResponse);
        sessions.values().forEach(e -> e.getWebSocket().send(bytes));
    }

    private void sendObject(WebsocketSession session, WSResponse res) {
        byte[] bytes = DataHelper.toByte(res);
        if(null != bytes) session.getWebSocket().send(bytes);
    }
}
